package com.example.crowdfunding.service.impl;

import com.example.crowdfunding.entity.Role;
import com.example.crowdfunding.entity.RoleExample;
import com.example.crowdfunding.mapper.RoleMapper;
import com.example.crowdfunding.service.api.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * The type Role service.
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {

        // 启用pageHelper
        PageHelper.startPage(pageNum, pageSize);

        // 执行查询
        List<Role> roleList = roleMapper.selectRoleByKeyword(keyword);

        // 封装为pageInfo对象返回
        return new PageInfo<>(roleList);
    }

    @Override
    public void addRole(Role role) {

        roleMapper.insertSelective(role);
    }

    @Override
    public void updateRole(Role role) throws DuplicateKeyException {

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andRoleNameEqualTo(role.getRoleName());
        List<Role> roles = roleMapper.selectByExample(roleExample);
        if (roles.size() > 0) {
            throw new DuplicateKeyException("提交的字段中存在具有唯一约束的字段");
        }
        roleMapper.updateByPrimaryKey(role);

    }

    @Override
    public void removeRolesByIds(List<Integer> roleIdList) {

        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdIn(roleIdList);
        roleMapper.deleteByExample(roleExample);
    }

    @Override
    public List<Role> getAssignedRole(Integer adminId) {

        return roleMapper.selectAssignedRole(adminId);
    }

    @Override
    public List<Role> getUnassignedRole(Integer adminId) {

        return roleMapper.selectUnassignedRole(adminId);
    }

}
